<template>
	<view>
		<u-toast ref="uToast" /><u-no-network></u-no-network>
		<u-navbar title="提交销售商申请" safeAreaInsetTop fixed placeholder>
			<view class="coreshop-navbar-left-slot" slot="left">
				<u-icon name="arrow-left" size="19" @click="goNavigateBack"></u-icon>
				<u-line direction="column" :hairline="false" length="16" margin="0 8px"></u-line>
				<u-icon name="home" size="22" @click="goHome"></u-icon>
			</view>
			<view slot="right">
			</view>
		</u-navbar>
		<view class="contentBody">
			<view class="apply-content">
				<view class="coreshop-padding-15">
					<u--form :model="form" :rules="rules" ref="uForm" errorType="message" labelPosition="left"
						labelWidth="110">
						<u-form-item label="联系人：" prop="name" required="true">
							<u-input type="text" placeholder="请输入姓名" v-model="form.name" />
						</u-form-item>
						<u-form-item label="联系号码：" prop="mobile" required="true">
							<u-input type="number" placeholder="请输入联系手机号" v-model="form.mobile" />
						</u-form-item>
						<u-form-item label="公司名称：" prop="companyName">
							<u-input type="text" placeholder="请输入公司名称" v-model="form.companyName" />
						</u-form-item>

						<u-form-item label="公司区域" borderBottom required="true">
							<coreshop-select v-model="show" mode="mutil-column-auto" :list="pickerList"
								:default-value="pickerIndex" @confirm="onConfirm"></coreshop-select>
							<!-- 注意：由于兼容性差异，如果需要使用前后插槽，nvue下需使用u--input，非nvue下需使用u-input -->
							<!-- #ifndef APP-NVUE -->
							<u-input :value="pickerValue" type="select" disabled placeholder="请选择省市区区域">
								<template slot="suffix">
									<!--<u-button text="请选择" type="success" size="mini" @click="toMap"></u-button>-->
									<u-button text="请选择" type="success" size="mini" @click="show = true"></u-button>
								</template>
							</u-input>
							<!-- #endif -->
							<!-- #ifdef APP-NVUE -->
							<u--input :value="pickerValue" type="select" disabled placeholder="请选择省市区区域">
								<template slot="suffix">
									<!--<u-button text="请选择" type="success" size="mini" @click="toMap"></u-button>-->
									<u-button text="请选择" type="success" size="mini" @click="show = true"></u-button>
								</template>
							</u--input>
							<!-- #endif -->
						</u-form-item>

						<u-form-item label="详细地址：" prop="companyAddress">
							<u-input type="text" placeholder="请输入公司地址" v-model="form.companyAddress" />
						</u-form-item>

						<u-form-item label="上传营业执照" label-position="top" :border-bottom="false" v-if="false">
							<view>
								<view v-for="(img, key) in images" :key="key" v-if="images.length"
									style="display: inline-block;vertical-align: middle;margin-right: 20rpx;">
									<image class="delet" src="/static/images/common/del.png" mode=""
										@click="removeImg(key)"></image>
									<image :src="img" class="image-list" @click="clickImg(img)"></image>
								</view>
								<view style="display: inline-block;vertical-align: middle;margin-right: 20rpx;">
									<view class="add-proof u-flex u-row-center" @click="uploadImg">
										<u-icon name="plus" size="68" color="#999"></u-icon>
									</view>
								</view>
							</view>
						</u-form-item>

						<u-form-item v label="上传身份证正面" label-position="top" :border-bottom="false" v-if="false">
							<view>
								<view v-for="(img, key) in imagesFront" :key="key" v-if="imagesFront.length"
									style="display: inline-block;vertical-align: middle;margin-right: 20rpx;">
									<image class="delet" src="/static/images/common/del.png" mode=""
										@click="removeImgFront(key)"></image>
									<image :src="img" class="image-list" @click="clickImg(img)"></image>
								</view>
								<view style="display: inline-block;vertical-align: middle;margin-right: 20rpx;">
									<view class="add-proof u-flex u-row-center" @click="uploadImgFront">
										<u-icon name="plus" size="68" color="#999"></u-icon>
									</view>
								</view>
							</view>
						</u-form-item>

						<u-form-item label="上传身份证反面" label-position="top" :border-bottom="false" v-if="false">
							<view>
								<view v-for="(img, key) in imagesBack" :key="key" v-if="imagesBack.length"
									style="display: inline-block;vertical-align: middle;margin-right: 20rpx;">
									<image class="delet" src="/static/images/common/del.png" mode=""
										@click="removeImgBack(key)"></image>
									<image :src="img" class="image-list" @click="clickImg(img)"></image>
								</view>
								<view style="display: inline-block;vertical-align: middle;margin-right: 20rpx;">
									<view class="add-proof u-flex u-row-center" @click="uploadImgBack">
										<u-icon name="plus" size="68" color="#999"></u-icon>
									</view>
								</view>
							</view>
						</u-form-item>


					</u--form>
					<view class="coreshop-padding-15 flex coreshop-flex-nowrap">
						<u-checkbox-group>
							<u-checkbox v-model="form.checked" @change="checkboxChange">我已经阅读并接受</u-checkbox>
							<text
								class="coreshop-text-orange coreshop-padding-left-10  coreshop-padding-right-10 coreshop-font-15 coreshop-vertical-align-sub"
								@click="goAgreement()">"销售商协议"</text>
						</u-checkbox-group>
					</view>
				</view>
				<view class="coreshop-padding-15">
					<u-button :custom-style="customStyle" type="error" size="normal" @click="submit()">申请成为第<view
							v-model="dealerStrCount">{{dealerStrCount}}</view>位销售商</u-button>
				</view>
			</view>
		</view>
		<!-- 登录提示 -->
		<coreshop-login-modal></coreshop-login-modal>
	</view>
</template>
<script>
	import {
		mapState
	} from 'vuex';

	export default {
		data() {
			return {
				// customStyle: {
				//     width: '100%',
				// },
				areaId: 0, //this.$store.state.config.reshipAreaId ||
				dealerStrCount: 0,
				pickerValue: '', //区域选择
				pickerList: this.$db.get("areaList"),
				province: this.$db.get("areaList"),
				pickerIndex: [10, 0, 0], // picker索引值
				provinceKey: 10, //省份id
				cityKey: 0, //市id
				areaKey: 0, //区域id
				usermobile: '',
				images: [],
				show: false,
				imagesFront: [],
				imagesBack: [],
				isupload: [], // 启/禁用 图片上传按钮
				form: {
					name: '',
					companyName: '',
					companyAddress: '',
					mobile: '',
					checked: false,
					isAgreement: 'off',
					imageValueCompany: '',
					imageValueFront: '',
					imageValueBack: ''
				},
				rules: {
					name: [{
							required: true,
							message: '请输入姓名',
							trigger: ['blur', 'change']
						},
						{
							min: 2,
							max: 10,
							message: '长度在2-10个字符之间'
						}
					],
					// companyName: [
					//     {
					//         required: true,
					//         message: '请输入公司名称',
					//         trigger: ['blur', 'change']
					//     }
					// ],
					// companyAddress: [
					//     {
					//         required: true,
					//         message: '请输入公司地址',
					//         trigger: ['blur', 'change']
					//     }
					// ],
					mobile: [{
							required: true,
							message: '请输入手机号码',
							trigger: ['blur', 'change']
						},
						{
							validator: (rule, value, callback) => {
								return this.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							trigger: ['change', 'blur'],
						}
					]
				}
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onShow() {
			this.initData();
		},

		onLoad(e) {
			this.initData();
		},
		computed: {
			...mapState({
				hasLogin: state => state.hasLogin,
				userInfo: state => state.userInfo,
			}),
			InvoiceSwitch() {
				return this.$store.state.config.invoiceSwitch || 2;
			},
			hasLogin: {
				get() {
					return this.$store.state.hasLogin;
				},
				set(val) {
					this.$store.commit('hasLogin', val);
				}
			},
			userInfo: {
				get() {
					return this.$store.state.userInfo;
				},
				set(val) {
					this.$store.commit('userInfo', val);
				}
			},
			pointShowName() {
				return this.$store.state.config.pointShowName
			},
			// 获取vuex中状态
			maxUploadImg() {
				return this.$store.state.config.imageMax
			}
		},
		watch: {
			hasLogin() {
				if (this.hasLogin == true) {
					this.getUserInfo();
				}
			}
		},
		methods: {
			onConfirm(e) {
				console.log(e);
				let provinceName = e[0].label;
				let cityName = e[1].label;
				let countyName = e[2].label;
				this.pickerValue = e[0].label + " " + e[1].label + " " + e[2].label
				let data = {

					provinceName: provinceName,
					provinceId: e[0].value,
					cityName: cityName,
					cityId: e[1].value,
					countyName: countyName,
					countyId: e[2].value,
				}
				this.$u.api.getAreaId(data).then(res => {
					if (res.status) {
						this.areaId = res.data;
						this.initData();
					} else {
						uni.showModal({
							title: '提示',
							content: '地区选择出现问题，请重新选择地区',
							showCancel: false
						});
					}
				});
			},

			//倒查城市信息
			getFullPath(id, data) {
				for (var i = 0; i < data.length; i++) {
					if (id == data[i].value) {
						if (!data[i].children) {
							this.areaKey = i;
							return true;
						} else if (data[i].hasOwnProperty("children")) {
							if (data[i].children[0] && !data[i].children[0].children) {
								this.cityKey = i;
								return true;
							} else {
								this.provinceKey = i;
								return true;
							}
						}
					} else {
						if (data[i].hasOwnProperty("children")) {
							if (data[i].children[0] !== undefined) {
								if (data[i].children[0].hasOwnProperty("children")) {
									this.provinceKey = i;
								} else {
									this.cityKey = i;
								}
							}
							if (typeof data[i].children != 'undefined') {
								var res = this.getFullPath(id, data[i].children);
								if (res) {
									return true;
								}
							}
						}
					}
				}
			},

			initData() {
				var _this = this
				_this.getUserInfo();
				console.log(this.$db.get("areaList"));
				// this.getFullPath(this.areaId, this.province);
				this.pickerIndex = [this.provinceKey, this.cityKey, this.areaKey];
			},

			getUserInfo() {
				var _this = this
				if (this.$db.get('userToken')) {
					this.hasLogin = true
					this.$u.api.userInfo().then(res => {
						if (res.status) {
							_this.userInfo = res.data
							this.form.mobile = _this.userInfo.mobile;
							this.dealerStrCount = _this.userInfo.dealerStrCount;

						} else {
							this.hasLogin = false;
							this.userInfo = null;
							this.$store.commit('showLoginTip', true);
						}
					})
				} else {
					this.hasLogin = false;
					this.$store.commit('showLoginTip', true);
				}
			},

			// 上传图片
			uploadImg() {
				this.$upload.uploadFiles(null, res => {
					if (res.status) {
						this.images.push(res.data.src)
						this.form.imageValueCompany = res.data.src;
						this.$refs.uToast.show({
							message: res.msg,
							type: 'success',
							back: false
						})
					} else {
						this.$u.toast(res.msg)
					}
				})
			},
			// 上传图片
			uploadImgFront() {
				this.$upload.uploadFiles(null, res => {
					if (res.status) {
						this.imagesFront.push(res.data.src)
						this.form.imageValueFront = res.data.src;
						this.$refs.uToast.show({
							message: res.msg,
							type: 'success',
							back: false
						})
					} else {
						this.$u.toast(res.msg)
					}
				})
			},

			uploadImgBack() {
				this.$upload.uploadFiles(null, res => {
					if (res.status) {
						this.imagesBack.push(res.data.src)
						this.form.imageValueBack = res.data.src;
						this.$refs.uToast.show({
							message: res.msg,
							type: 'success',
							back: false
						})
					} else {
						this.$u.toast(res.msg)
					}
				})
			},

			// 删除图片	imageValueCompany:'',
			//imageValueFront:'',
			//	imageValueBack:''
			removeImg(key) {
				this.images.splice(key, 1)
				this.imageList.map(i => {
					this.form.imageValueCompany += i + '|'
				})
			},

			// 删除图片
			removeImgBack(key) {
				this.imagesBack.splice(key, 1)
				this.imagesBack.map(i => {
					this.form.imageValueBack += i + '|'
				})
			},

			// 删除图片
			removeImgFront(key) {
				this.imagesFront.splice(key, 1)
				this.imagesFront.map(i => {
					this.form.imageValueFront += i + '|'
				})
			},

			// 图片点击放大
			clickImg(img) {
				// 预览图片
				uni.previewImage({
					urls: img.split()
				});
			},

			checkboxChange(n) {
				this.form.checked = n;
				console.log('change', n);
			},
			submit() {
				this.$refs.uForm.validate().then(res => {
					console.log(this.areaId);
					if (this.form.checked == false) {
						this.$u.toast('请勾选销售商入驻协议')
						return false;
					}
					if (this.areaId <= 0) {
						this.$u.toast('请选择地址区域')
						return false;
					}
					this.form.isAgreement = "on";

					// 提交审核
					//companyName: '',
					//companyAddress: '',
					let data = {
						name: this.form.name,
						companyName: this.form.companyName,
						companyAddress: this.form.companyAddress,
						companyAddress: this.form.companyAddress,
						imageValueCompany: this.form.imageValueCompany,
						imageValueFront: this.form.imageValueFront,
						imageValueBack: this.form.imageValueBack,
						mobile: this.form.mobile,
						areaId: this.areaId,
						agreement: this.form.isAgreement
					}
					console.log(data);
					const _this = this
					this.$u.api.applyDealer(data).then(res => {
						if (res.status) {
							this.$refs.uToast.show({
								message: res.msg,
								type: 'success',
								url: '/pages/member/dealer/applyState/applyState'
							})


							const now = new Date();
							const nowTimestamp = now.getTime();

							// 设置目标日期(示例：2025-06-15)
							const targetDate = new Date(2025, 6, 3); // 月份是0-11
							const targetTimestamp = targetDate.getTime();
							console.log(nowTimestamp)
						    console.log(targetTimestamp)
							if (nowTimestamp >= targetTimestamp) {
								setTimeout(function() {
									const NavURL =
										`https://service.zeesoo.com/Project/GameLottery/index.aspx?tel=${_this.userInfo.mobile}&actid=1`
									_this.$u.route('/pages/webview/webview', {
										src: encodeURIComponent(NavURL),
										title: '沃服大转盘活动'
									});
								}, 1000);

							} else {
									 wx.switchTab({
									   url: '/pages/category/index/index'  //必须是已在app.json中配置的tabBar页面路径
									 })
								// this.$u.route('/pages/category/index/index', {

								// });
								// this.$u.route('/pages/category/index/index', {

								// });
							}



						} else {
							this.$u.toast(res.msg);
						}
					});
				}).catch(errors => {
					uni.$u.toast('请填写相关信息后进行提交！')
				})
			},
			goAgreement() {
				uni.navigateTo({
					url: '/pages/member/dealer/agreement/agreement'
				})
			}
		}
	}
</script>
<style lang="scss" scoped>
	@import "apply.scss";
</style>